package com.wangzhenyu.learn.test.java.io

import java.io.*

@Suppress("UNUSED")
object InstanceInputStream {

    //FileInputStream
    fun test01() {
        val path = "D:\\picture\\test.txt"
        var fileInputStream: FileInputStream? = null
        var read = 0

        //一次读取八个字节
        val byte = ByteArray(8)
        try {
            fileInputStream = FileInputStream(path)
            //返回-1,表示读取完成
            while (read != -1) {
                read = fileInputStream.read(byte)
                if (read != -1) print(String(byte, 0, read))
            }
        } catch (e: Exception) {
            //
        } finally {
            fileInputStream?.close()
        }
    }

    //拷贝文件
    fun test02() {
        val inputPath = "D:\\tupian\\feifei.jpg"
        val outputPath = "D:\\giao.jpg"
        var fileInputStream: FileInputStream? = null
        var fileOutputStream: FileOutputStream? = null
        var read = 0

        //一次读取128个字节
        val byte = ByteArray(128)
        try {
            fileInputStream = FileInputStream(inputPath)
            fileOutputStream = FileOutputStream(outputPath)
            //返回-1,表示读取完成
            while (read != -1) {
                read = fileInputStream.read(byte)
                if (read != -1) fileOutputStream.write(byte, 0, read)
            }
        } catch (e: Exception) {
            //
        } finally {
            fileInputStream?.close()
            fileOutputStream?.close()
        }
    }

    //BufferInputStream拷贝文件
    fun test03() {
        val inputPath = "D:\\tupian\\feifei.jpg"
        val outputPath = "D:\\giao.jpg"
        var bufferedInputStream: BufferedInputStream? = null
        var bufferedOutputStream: BufferedOutputStream? = null
        var read = 0

        //一次读取128个字节
        val byte = ByteArray(128)
        try {
            bufferedInputStream = BufferedInputStream(FileInputStream(inputPath))
            bufferedOutputStream = BufferedOutputStream(FileOutputStream(outputPath))
            //返回-1,表示读取完成
            while (read != -1) {
                read = bufferedInputStream.read(byte)
                if (read != -1) bufferedOutputStream.write(byte, 0, read)
            }
        } catch (e: Exception) {
            //
        } finally {
            bufferedInputStream?.close()
            bufferedOutputStream?.close()
        }
    }

    //ObjectInputStream
    fun test04() {
        val path = "D:\\picture\\test.txt"
        var objectInputStream: ObjectInputStream? = null
        try {
            objectInputStream = ObjectInputStream(FileInputStream(path))
            val temp = objectInputStream.readObject()
            println(temp)
            println((temp as StreamObject).name)
        } catch (e: Exception) {
            //
        } finally {
            objectInputStream?.close()
        }
    }

}